<?php declare(strict_types=1);

namespace App\Http\Controller;


use Swoft\Context\Context;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\Middleware;
use App\Http\Middleware\LogMiddleware;
use Swoft\Http\Server\Annotation\Mapping\Middlewares;

/**
 * Class HomeController
 * @Middlewares({
 *     @Middleware("LogMiddleware::class"),
 *     @Middleware("AuthMiddleware::class")
 * })
 * @Controller()
 */
class BaseController
{
   public function response($code =10000, $data = [], $msg = '', $tip_code = 0 )
   {
       $request = Context::mustGet()->getRequest();
       if(!$data && is_array($data)) $data = new \stdClass();
       if(is_null($data)) $data = null;
       if(!isset(config('lang_'. $request->lang)[$code]) && $code != 10000) $request->lang = 'en';
       if(!$msg) $msg = ($code === 10000) ? '' : config('lang_'. $request->lang.'.'.$code);
       if($tip_code && is_numeric($tip_code)){
           $tips = config('lang_'. $this->request->lang.'.'.$tip_code);
       } elseif($tip_code && !is_numeric($tip_code)){
           $tips = $tip_code;
       } else{
           $tips = '';
       }
       $request = Context::mustGet()->getRequest();
       return Context::mustGet()->getResponse()
           ->withContentType(ContentType::JSON)
           ->withData([
               'run_time' => microtime(true) - $request->run_start,
               'code' => $code,
               'msg'    => $msg,
               'tips'   => $tips,
               'data' => $data,
           ]);
   }
}
